package org.jfk.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jfk.core.utils.I18nUtil;
import org.jfk.sys.user.User;

public class MyDBRealm extends AuthorizingRealm {

	/*
	 * 鉴权处理
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        String loginName = (String) getAvailablePrincipal(principals);
        User user = User.dao.findByLoginName(loginName);
        
        
		// TODO Auto-generated method stub
        Set<String> roleSet = new HashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleSet);
        info.setStringPermissions(null);
        return info;

	}
	


	/*
	 * 认证处理
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String loginName = upToken.getUsername();
        
        if (loginName == null) {
            throw new UnknownAccountException(I18nUtil.getValueByKey("admin.login.error.no_user"));
        }
        User user = User.dao.findByLoginName(loginName);
        if(user == null || user.getStr("password")==null)
            throw new UnknownAccountException(I18nUtil.getValueByKey("admin.login.error.no_user"));
        
        String pwd =  user.getStr("password");
        
        AuthenticationInfo info = new SimpleAuthenticationInfo(loginName, pwd, getName());

        return info;
	}

}
